package com.ruoyi.womp.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Sorts;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.security.PermissionUtils;
import com.ruoyi.womp.domain.mongo.WompAlarm;
import com.ruoyi.womp.service.ISqlQueryService;
import com.ruoyi.womp.service.RealTimeServie;
import com.ruoyi.womp.service.WompServiceUtil;
import com.ruoyi.womp.tools.DateUtil;
import com.ruoyi.womp.tools.Result;

@Controller
@RequestMapping("/realtime")
public class RealTimeController extends BaseController {

	private String prefix = "womp/";

	@Autowired
	WompServiceUtil wompServiceUtil;

	@Autowired
	RealTimeServie realTimeServie;

	@Autowired
	ISqlQueryService sqlQueryService;

	@Autowired
	MongoTemplate mongoTemplate;

	@RequestMapping(value = "/index")
	public String index(HttpServletRequest req, Model model) {
		super.init(model);

		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");
		// 机构衡器列表
		List<Map<String, Object>> waList = realTimeServie.getDeptWeighingApparatusList(loginName);

		model.addAttribute("waList", waList);
		return prefix + "index";
	}

	@RequestMapping(value = "/main")
	public String main(HttpServletRequest req, Model model) {
		super.init(model);

		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");
		// 机构衡器列表
		List<Map<String, Object>> waList = realTimeServie.getDeptWeighingApparatusList(loginName);

		model.addAttribute("waList", waList);
		return prefix + "main";
	}

	/**
	 * 单个衡器展示页面
	 * 
	 * @param req
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/washow")
	public String washow(HttpServletRequest req, Model model) {
		super.init(model);

		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");

		String waCode = req.getParameter("waCode");

		// 衡器信息
		Map<String, Object> waMap = new HashMap<String, Object>();
		if (null == waCode || waCode.trim().equals("")) {
			waMap = realTimeServie.getDeptDefaultWeighingApparatus(loginName);
			if (null != waMap) {
				waCode = waMap.get("wacode").toString();
			}
		} else {
			waMap = realTimeServie.getWaInfoMap(waCode);
		}
		if (null != waMap) {
			// 衡器配置信息
			List<Map<String, Object>> waconfigList = realTimeServie.getWaTypeConfigData(waMap.get("type").toString(),
					waCode);

			List<Map<String, Object>> waconfigColorList = realTimeServie
					.getWaTypeConfigColorData(waMap.get("type").toString());
			model.addAttribute("waMap", waMap);
			model.addAttribute("waconfigList", waconfigList);
			model.addAttribute("waconfigColorList", waconfigColorList);

			long num = realTimeServie.getAlarmNum(waCode);
			model.addAttribute("alarmNum", num);
		}

		return prefix + "washow";
	}

	@RequestMapping(value = "/wacharts")
	public String wacharts(HttpServletRequest req, Model model) {
		super.init(model);

		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");

		String waCode = req.getParameter("waCode");

		// 衡器信息
		Map<String, Object> waMap = new HashMap<String, Object>();
		if (null == waCode || waCode.trim().equals("")) {
			waMap = realTimeServie.getDeptDefaultWeighingApparatus(loginName);
			waCode = waMap.get("wacode").toString();
		} else {
			waMap = realTimeServie.getWaInfoMap(waCode);
		}
		if (null != waMap) {
			// 衡器配置信息
			List<Map<String, Object>> waconfigList = realTimeServie.getWaTypeConfigData(waMap.get("type").toString(),
					waCode);

			model.addAttribute("waMap", waMap);
			model.addAttribute("waconfigList", waconfigList);
		}

		model.addAttribute("date", DateUtil.formatDate(Calendar.getInstance().getTime()));
		return prefix + "wacharts";
	}

	@RequestMapping(value = "/wachartshis")
	public String wachartshis(HttpServletRequest req, Model model) {
		super.init(model);

		String token = req.getParameter("token");
		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");

		String waCode = req.getParameter("waCode");

		List<Map<String, Object>> waList = realTimeServie.getDeptWeighingApparatusList(loginName);
		// 衡器信息
		Map<String, Object> waMap = new HashMap<String, Object>();
		if (null == waCode || waCode.trim().equals("")) {
			waMap = realTimeServie.getDeptDefaultWeighingApparatus(loginName);
			waCode = waMap.get("wacode").toString();
		} else {
			waMap = realTimeServie.getWaInfoMap(waCode);
		}
		List<Map<String, Object>> waElementList = wompServiceUtil.getWaElementNum(waCode);

		model.addAttribute("waMap", waMap);
		model.addAttribute("waList", waList);
		model.addAttribute("waElementList", waElementList);
		model.addAttribute("date", DateUtil.formatDate(Calendar.getInstance().getTime()));
		model.addAttribute("token", token);

		return prefix + "wachartshis";
	}

	@ResponseBody
	@RequestMapping(value = "/waElementList")
	public Result<?> waElementList(HttpServletRequest req, Model model) {
		String waCode = req.getParameter("waCode");
		List<Map<String, Object>> waElementList = wompServiceUtil.getWaElementNum(waCode);
		return Result.OK(waElementList);
	}

	@ResponseBody
	@RequestMapping(value = "/charthis")
	public Result<?> charthis(HttpServletRequest req, Model model) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Document> list = new ArrayList<Document>();

		String timeInterval = req.getParameter("timeInterval");
		String waCode = req.getParameter("waCode");
		// 小时、分钟数据
		if (timeInterval.equals("1") || timeInterval.equals("2")) {
			String year = req.getParameter("year");
			String month = req.getParameter("month");
			Pattern pattern = null;
			if (timeInterval.equals("1")) {
				pattern = Pattern.compile("(" + year + "-\\d{2}-\\d{2}) (\\d{2}):00", Pattern.CASE_INSENSITIVE);
			} else if (timeInterval.equals("2")) {
				pattern = Pattern.compile("(" + year + "-" + month + "-\\d{2}) (\\d{2}):(\\d{2}):00",
						Pattern.CASE_INSENSITIVE);
			}
			BasicDBObject basicDBObject = new BasicDBObject();
			if (null != waCode && waCode.length() > 0) {
				basicDBObject.put("waCode", new BasicDBObject("$eq", waCode));
				basicDBObject.put("time", new BasicDBObject("$regex", pattern));

				Bson orderBy = Sorts.ascending("time");
				FindIterable<Document> find = mongoTemplate.getCollection("WRD_" + waCode + "_M" + year)
						.find(basicDBObject).sort(orderBy);
				Iterator<Document> iterator = find.cursor();
				while (iterator.hasNext()) {
					Document doc = iterator.next();
					list.add(doc);
				}
			}
		}
		// 秒数据
		else if (timeInterval.equals("3")) {
			Integer hour = Integer.parseInt(req.getParameter("hour"));
			hour--;

			String date = req.getParameter("date");
			if (null == date) {
				date = DateUtil.formatDate(Calendar.getInstance().getTime());
			}

			// "{'$and':[{'waCode':'H002'},{'time':{'$gt':'2022-03-0200:00:00'}},{'time':{'$lt':'2022-03-0223:00:00'}}]}");
			// {'$and':[{'waCode':'H002'},{'time':{'$gt':'2022-03-0200:00:00'}},{'time':{'$lt':'2022-03-0223:00:00'}}]}
			Pattern pattern = Pattern.compile("^" + date + " " + (hour > 9 ? hour : "0" + hour) + ".*$",
					Pattern.CASE_INSENSITIVE);
			BasicDBObject basicDBObject = new BasicDBObject();
			if (null != waCode && waCode.length() > 0) {
				basicDBObject.put("waCode", new BasicDBObject("$eq", waCode));
				basicDBObject.put("time", new BasicDBObject("$regex", pattern));

				Bson orderBy = Sorts.ascending("time");
				FindIterable<Document> find = mongoTemplate
						.getCollection("WRD_" + waCode + "_S" + date.substring(0, 7).replace("-", ""))
						.find(basicDBObject).sort(orderBy);
				Iterator<Document> iterator = find.cursor();
				while (iterator.hasNext()) {
					Document doc = iterator.next();
					list.add(doc);
				}
			}
		}

		List<Map<String, Object>> elementMap = wompServiceUtil.getWaElementNum(waCode);
		resultMap.put("elementMap", elementMap);
		resultMap.put("data", list);
		return Result.OK(resultMap);
	}

	@RequestMapping(value = "/waalarmlist")
	public String waalarmlist(HttpServletRequest req, Model model) {

		// String loginName = (String)
		// PermissionUtils.getPrincipalProperty("loginName");

		// List<Map<String, Object>> waList =
		// realTimeServie.getDeptWeighingApparatusList(loginName);
		// List<Map<String, Object>> waElementList =
		// realTimeServie.getWaTypeConfigList();

		return prefix + "alarmList";
	}

	@ResponseBody
	@RequestMapping(value = "/alarmList")
	public TableDataInfo alarmList(HttpServletRequest req, Model model) {
		startPage();

		Integer pageSize = Integer.parseInt(req.getParameter("pageSize"));
		Integer pageNum = Integer.parseInt(req.getParameter("pageNum"));
		String waCode = req.getParameter("waCode");
		String alarmType = req.getParameter("ecode");
		String alarmState = req.getParameter("state");
		String beginDate = req.getParameter("beginDate");
		String endDate = req.getParameter("endDate");

		Query query = new Query();
		if (null != waCode && waCode.trim().length() > 0) {
			query.addCriteria(Criteria.where("waCode").is(waCode));
		}
		if (null != alarmType && alarmType.length() > 0) {
			query.addCriteria(Criteria.where("code").is(alarmType));
		}
		if (null != alarmState && alarmState.length() > 0) {
			query.addCriteria(Criteria.where("state").is(Integer.parseInt(alarmState)));
		}
		if (null != beginDate && beginDate.length() > 0 && null != endDate && endDate.length() > 0) {
			query.addCriteria(Criteria.where("time").gte(beginDate + " 00:00:00").lte(endDate + " 23:59:59"));
		}

		long count = mongoTemplate.count(query, "womp_alarm_data");
		query.with(Sort.by(Sort.Direction.DESC, "time"));
		query.limit(pageSize);
		query.skip((pageNum - 1) * pageSize);

		List<WompAlarm> list = mongoTemplate.find(query, WompAlarm.class, "womp_alarm_data");

		TableDataInfo rspData = new TableDataInfo();
		rspData.setCode(0);
		rspData.setRows(list);
		rspData.setTotal(count);

		return rspData;
	}

	@RequestMapping(value = "/waState")
	public String waState(HttpServletRequest req, Model model) {
		super.init(model);

		String waCode = req.getParameter("waCode");
		Map<String, Object> waMap = realTimeServie.getWaInfoMap(waCode);
		model.addAttribute("waMap", waMap);

		// 月第一天和最后一天
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.add(Calendar.DAY_OF_MONTH, -1);
		// 格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String lastDayOfMonth = sdf.format(cal.getTime());
		cal.set(Calendar.DAY_OF_MONTH, 1);
		String firstDayOfMonth = sdf.format(cal.getTime());

		Aggregation monthAggregate = Aggregation.newAggregation(
				Aggregation.match(Criteria.where("waCode").is(waCode).and("time").lte(lastDayOfMonth + " 23:59:59")),
				Aggregation.project("time").andExpression("time").substring(0, 7).as("month"),
				Aggregation.group("month").count().as("num"),
				Aggregation.project("month", "num").and("month").previousOperation(),
				Aggregation.sort(Sort.Direction.ASC, "month"));
		AggregationResults<JSONObject> monthResults = mongoTemplate.aggregate(monthAggregate, "womp_alarm_data",
				JSONObject.class);
		List<JSONObject> monthAlarmList = monthResults.getMappedResults();
		model.addAttribute("monthAlarmList", monthAlarmList);

		Aggregation dayAggregation = Aggregation.newAggregation(
				Aggregation.match(Criteria.where("waCode").is(waCode).and("time").gte(firstDayOfMonth + " 00:00:00")
						.lte(lastDayOfMonth + " 23:59:59")),
				Aggregation.project("time").andExpression("time").substring(0, 10).as("day"),
				Aggregation.group("day").count().as("num"),
				Aggregation.project("day", "num").and("day").previousOperation(),
				Aggregation.sort(Sort.Direction.ASC, "day"));
		AggregationResults<JSONObject> dayResults = mongoTemplate.aggregate(dayAggregation, "womp_alarm_data",
				JSONObject.class);
		List<JSONObject> dayAlarmList = dayResults.getMappedResults();
		model.addAttribute("dayAlarmList", dayAlarmList);

		// 备件库存
		String sql = " SELECT wsp.name,wsp.model,wsp.spec,(select sum(num) from womp_spare_parts_inout wspi where wspi.spare_part_id=wsp.id) num "
				+ " FROM womp_spare_parts wsp order by num limit 7 ";
		List<Map<String, Object>> sparePartsList = sqlQueryService.queryMapList(sql);
		model.addAttribute("sparePartsList", sparePartsList);

		// 告警列表
		Query query = new Query();
		query.addCriteria(Criteria.where("waCode").is(waCode));
		query.with(Sort.by(Sort.Direction.DESC, "time"));
		query.limit(9);
		List<WompAlarm> alarmList = mongoTemplate.find(query, WompAlarm.class, "womp_alarm_data");
		model.addAttribute("alarmList", alarmList);

		// 工单列表
		sql = " select wwo.id,wwo.wa_code,wwo.type,wwo.osi_type,wwo.files,wwo.alarm_id,wwo.state,ifnull(wwo.ecode,'') ecode,wwo.handling_opinions,"
				+ " wwo.handler,wwo.update_by,DATE_FORMAT(wwo.update_time,'%Y-%m-%d') update_time,wwo.create_by, "
				+ " DATE_FORMAT(wwo.create_time,'%Y-%m-%d') create_time,we.name ename,su.user_name handlerName,sdd.dict_label workorderType, "
				+ " sdd1.dict_label osiTypeName,sdd2.dict_label stateName from womp_work_order wwo "
				+ " left join womp_element we on wwo.ecode=we.code inner join sys_user su on su.login_name=wwo.handler "
				+ " left join sys_dict_data sdd on sdd.dict_value=wwo.type and sdd.dict_type='work_order_type'"
				+ " left join sys_dict_data sdd1 on sdd1.dict_value=wwo.osi_type and sdd1.dict_type='sys_osi_type' "
				+ " left join sys_dict_data sdd2 on sdd2.dict_value=wwo.state and sdd2.dict_type='work_order_state' where wa_code='"
				+ waCode + "' order by create_time desc limit 7 ";
		List<Map<String, Object>> workOrderList = sqlQueryService.queryMapList(sql);
		model.addAttribute("workOrderList", workOrderList);

		// 巡检列表
		sql = " select wor.*,sdd.dict_label,su.user_name from womp_osi_record wor left join sys_dict_data sdd "
				+ " on wor.osi_plan_type=sdd.dict_value and sdd.dict_type='sys_osi_type' inner join sys_user su on su.login_name=wor.osi_user"
				+ " where wa_code='" + waCode + "' order by create_time desc limit 7 ";
		List<Map<String, Object>> osiRecordList = sqlQueryService.queryMapList(sql);
		model.addAttribute("osiRecordList", osiRecordList);

		long num = realTimeServie.getAlarmNum(waCode);
		model.addAttribute("alarmNum", num);

		return prefix + "waState";
	}

	@RequestMapping(value = "/waWorkOrderList")
	public String waWorkOrderList(HttpServletRequest req, Model model) {

		return prefix + "waWorkOrderList";
	}

	@ResponseBody
	@RequestMapping(value = "/workOrderList")
	public TableDataInfo workOrderList(HttpServletRequest req, Model model) {
		startPage();

		String waCode = req.getParameter("waCode");
		String type = req.getParameter("type");
		String alarmId = req.getParameter("alarmId");
		String ecode = req.getParameter("ecode");
		String workOrderState = req.getParameter("state");
		String beginDate = req.getParameter("beginDate");
		String endDate = req.getParameter("endDate");

		Integer state = null;
		if (null != workOrderState && workOrderState.length() > 0) {
			state = Integer.parseInt(workOrderState);
		}

		List<Map<String, Object>> list = realTimeServie.getWorkOrderList(waCode, type, alarmId, state, ecode, beginDate,
				endDate);

		List<String> idList = new ArrayList<String>();
		for (Map<String, Object> map : list) {
			if (null != map.get("alarm_id") && map.get("alarm_id").toString().length() > 0) {
				idList.add(map.get("alarm_id").toString());
			}
		}
		List<Map> alarmInfoList = realTimeServie.getAlarmInfoList(idList);
		for (Map workOrderMap : list) {
			// 告警工单时加载告警数据
			if (workOrderMap.get("type").toString().equals("1")) {
				for (Map alarmMap : alarmInfoList) {
					if (workOrderMap.get("alarm_id").toString().equals(alarmMap.get("_id").toString())) {
						workOrderMap.put("content", alarmMap.get("message"));
						break;
					}
				}
			}
		}

		return getDataTable(list);
	}

	@RequestMapping(value = "/toNewWorkOrder")
	public String toNewWorkOrder(HttpServletRequest req, Model model) {

		String alarmId = req.getParameter("alarmId");
		Map<String, Object> alarmMap = realTimeServie.getAlarmInfo(alarmId);

		String waCode = alarmMap.get("waCode").toString();
		Map<String, Object> waInfoMap = realTimeServie.getWaInfoMap(waCode);

		String elementCode = alarmMap.get("code").toString();
		List<Map<String, Object>> sysHandleOptions = wompServiceUtil.getElementSystemHandelOptions(elementCode);

		String ename = realTimeServie.getEname(elementCode);
		alarmMap.put("ename", ename);

		model.addAttribute("sysHandleOptions", sysHandleOptions);
		model.addAttribute("alarmMap", alarmMap);
		model.addAttribute("waInfoMap", waInfoMap);
		model.addAttribute("userList", wompServiceUtil.getDetpUserList());
		return prefix + "workOrder";
	}

	@ResponseBody
	@PostMapping(value = "/saveWorkOrder")
	public AjaxResult saveWorkOrder(HttpServletRequest req) {

		realTimeServie.saveWorkOrder(req);

		return success();
	}

	@RequestMapping(value = "/toWorkOrderHandle")
	public String toWorkOrder(HttpServletRequest req, Model model) {

		String loginName = (String) PermissionUtils.getPrincipalProperty("loginName");
		model.addAttribute("loginName", loginName);
		String workOrderId = req.getParameter("workOrderId");
		Map<String, Object> workOrderMap = realTimeServie.getWorkOrderMap(workOrderId);
		String waCode = workOrderMap.get("wa_code").toString();
		Map<String, Object> waInfoMap = realTimeServie.getWaInfoMap(waCode);
		model.addAttribute("waInfoMap", waInfoMap);
		model.addAttribute("workOrderMap", workOrderMap);

		String workorderType = workOrderMap.get("type").toString();
		if (workorderType.equals("1")) {
			String alarmId = null == workOrderMap.get("alarm_id") ? null : workOrderMap.get("alarm_id").toString();
			Map<String, Object> alarmMap = realTimeServie.getAlarmInfo(alarmId);

			String elementCode = alarmMap.get("code").toString();
			List<Map<String, Object>> sysHandleOptions = wompServiceUtil.getElementSystemHandelOptions(elementCode);

			String ename = realTimeServie.getEname(elementCode);
			alarmMap.put("ename", ename);

			model.addAttribute("sysHandleOptions", sysHandleOptions);
			model.addAttribute("alarmMap", alarmMap);

			return prefix + "workOrderHandle";
		} else if (workorderType.equals("2")) {
			String osiTypeString = workOrderMap.get("osi_type").toString();
			String sql = " select * from womp_osi_record where workorder_id=" + workOrderId;
			Map<String, Object> osiRecordMap = sqlQueryService.queryOne(sql);

			if (null != osiRecordMap) {
				sql = " select id,name,remark from womp_osi_item woi where osi_record_id=" + osiRecordMap.get("id");
				List<Map<String, Object>> osiRecordItemlist = sqlQueryService.queryMapList(sql);

				model.addAttribute("osiRecordMap", osiRecordMap);
				model.addAttribute("osiRecordItemlist", osiRecordItemlist);
			} else {

				sql = " select * from womp_osi_item where FIND_IN_SET(id,(select osi_items from womp_osi_plan wop where wop.wa_code='"
						+ waCode + "' and plan_type=" + osiTypeString + ")) ";
				List<Map<String, Object>> osiIteList = sqlQueryService.queryMapList(sql);
				model.addAttribute("osiIteList", osiIteList);
			}
			return prefix + "workOrderOsiHandle";
		}
		return "";
	}

	@ResponseBody
	@PostMapping(value = "/workOrderHandle")
	public AjaxResult workOrderHandle(HttpServletRequest req) {

		realTimeServie.handleWorkOrder(req);
		return success();
	}

	@RequestMapping(value = "/toWorkOrderDetail")
	public String toWorkOrderDetail(HttpServletRequest req, Model model) {

		String workOrderId = req.getParameter("workOrderId");
		Map<String, Object> workOrderMap = realTimeServie.getWorkOrderMap(workOrderId);
		String waCode = workOrderMap.get("wa_code").toString();
		Map<String, Object> waInfoMap = realTimeServie.getWaInfoMap(waCode);
		model.addAttribute("waInfoMap", waInfoMap);
		model.addAttribute("workOrderMap", workOrderMap);

		String workorderType = workOrderMap.get("type").toString();
		if (workorderType.equals("1")) {
			String alarmId = null == workOrderMap.get("alarm_id") ? null : workOrderMap.get("alarm_id").toString();
			Map<String, Object> alarmMap = realTimeServie.getAlarmInfo(alarmId);

			String elementCode = alarmMap.get("code").toString();
			List<Map<String, Object>> sysHandleOptions = wompServiceUtil.getElementSystemHandelOptions(elementCode);

			String ename = realTimeServie.getEname(elementCode);
			alarmMap.put("ename", ename);

			model.addAttribute("sysHandleOptions", sysHandleOptions);
			model.addAttribute("alarmMap", alarmMap);

			return prefix + "workOrderDetail";
		} else if (workorderType.equals("2")) {
			String sql = " select * from womp_osi_record where workorder_id=" + workOrderId;
			Map<String, Object> osiRecordMap = sqlQueryService.queryOne(sql);

			sql = " SELECT woi.name,sdd.dict_label osi_item_state,wori.remark FROM womp_work_order wwo "
					+ " inner join womp_osi_plan wop on wwo.wa_code=wop.wa_code "
					+ " left join womp_osi_record wor on wwo.id=wor.workorder_id "
					+ " inner join womp_osi_record_item wori on wor.id=wori.osi_record_id "
					+ " inner join womp_osi_item woi on wori.osi_item_id=woi.id "
					+ " left join sys_dict_data sdd on sdd.dict_value=wori.osi_result where wwo.id=" + workOrderId
					+ " and wop.plan_type=wwo.osi_type and sdd.dict_type='sys_ois_item_state' ";
			List<Map<String, Object>> osiRecordItemlist = sqlQueryService.queryMapList(sql);

			model.addAttribute("osiRecordMap", osiRecordMap);
			model.addAttribute("osiRecordItemlist", osiRecordItemlist);
			return prefix + "workOrderDetail";
		}
		return "";
	}

	@RequestMapping(value = "/newOsiWorkorder")
	public String newOsiWorkorder(HttpServletRequest req, Model model) {

		String waCode = req.getParameter("waCode");
		String planType = req.getParameter("planType");

		model.addAttribute("waCode", waCode);
		model.addAttribute("osiType", planType);
		return prefix + "workOrderOsi";
	}

	@ResponseBody
	@PostMapping(value = "/saveOsiWorkorder")
	public AjaxResult saveOsiWorkorder(HttpServletRequest req) {
		String waCode = req.getParameter("waCode");
		String workorderType = req.getParameter("workorderType");
		String osiType = req.getParameter("osiType");
		String osiUser = req.getParameter("osiUser");
		String handlingOpinions = req.getParameter("handlingOpinions");

		realTimeServie.createWorkorder(waCode, osiType, osiUser, handlingOpinions);
		return success();
	}

	@RequestMapping(value = "/openOsiRecordDetail")
	public String openOsiRecordDetail(HttpServletRequest req, Model model) {

		String id = req.getParameter("id");
		String sql = " select * from womp_osi_record where id=" + id;
		Map<String, Object> osiRecordMap = sqlQueryService.queryOne(sql);

		sql = " SELECT woi.name,sdd.dict_label osi_item_state,wori.remark FROM womp_osi_record wor "
				+ " inner join womp_osi_record_item wori on wor.id=wori.osi_record_id "
				+ " inner join womp_osi_item woi on wori.osi_item_id=woi.id "
				+ " left join sys_dict_data sdd on sdd.dict_value=wori.osi_result where wor.id=" + id
				+ " and sdd.dict_type='sys_ois_item_state' ";
		List<Map<String, Object>> osiRecordItemlist = sqlQueryService.queryMapList(sql);

		model.addAttribute("osiRecordMap", osiRecordMap);
		model.addAttribute("osiRecordItemlist", osiRecordItemlist);
		return prefix + "osiDetail";
	}

	@ResponseBody
	@PostMapping(value = "/alarm/allIgnore")
	public AjaxResult allIgnore(HttpServletRequest req) {

		realTimeServie.allIgnoreAlarm();

		return success();
	}

	@ResponseBody
	@PostMapping(value = "/alarm/conditionIgnore")
	public AjaxResult conditionIgnore(HttpServletRequest req) {

		realTimeServie.conditionIgnoreAlarm(req);

		return success();
	}

	@ResponseBody
	@PostMapping(value = "/alarm/checkIgnore")
	public AjaxResult checkIgnore(HttpServletRequest req) {

		realTimeServie.checkIgnoreAlarm(req);

		return success();
	}

	@ResponseBody
	@PostMapping(value = "/alarm/conditionDelete")
	public AjaxResult conditionDelete(HttpServletRequest req) {

		realTimeServie.conditionDeleteAlarm(req);

		return success();
	}

	@RequestMapping(value = "/toWorkOrderHandleHis")
	public String toWorkOrderHandleHis(HttpServletRequest req, Model model) {

		return prefix + "workOrderHandleHis";
	}

	@ResponseBody
	@RequestMapping(value = "/workOrderHis")
	public TableDataInfo workOrderHis(HttpServletRequest req, Model model) {
		startPage();

		String ecode = req.getParameter("ecode");

		List<Map<String, Object>> list = realTimeServie.getWorkOrderList(null, null, null, null, ecode, null, null);

		List<String> idList = new ArrayList<String>();
		for (Map<String, Object> map : list) {
			idList.add(map.get("alarm_id").toString());
		}
		List<Map> alarmInfoList = realTimeServie.getAlarmInfoList(idList);
		for (Map workOrderMap : list) {
			for (Map alarmMap : alarmInfoList) {
				if (workOrderMap.get("alarm_id").toString().equals(alarmMap.get("_id").toString())) {
					workOrderMap.put("content", alarmMap.get("message"));
					break;
				}
			}
		}

		return getDataTable(list);
	}

	@RequestMapping(value = "/openHandlingOpinions")
	public String openHandlingOpinions(HttpServletRequest req, Model model) {

		String id = req.getParameter("id");
		String sql = " select * from womp_handling_opinions where id=" + id;
		Map<String, Object> map = sqlQueryService.queryOne(sql);
		model.addAttribute("map", map);
		return prefix + "handlingOpinions";
	}

	@ResponseBody
	@PostMapping(value = "/alarm/setAlarmMusicFlag")
	public AjaxResult setAlarmMusicFlag(HttpServletRequest req) {

		String waCode = req.getParameter("waCode");
		String musicFlag = req.getParameter("musicFlag");
		String sql = " update womp_weighing_apparatus set alarm_music='" + musicFlag + "' where code='" + waCode + "' ";
		sqlQueryService.executeSql(sql);
		return success();
	}

}
